<?php

/**
 * Class File_trace_service 文件轨迹相关业务逻辑
 * @author: Calvin
 * @email : hongbinfu@163.com
 * @readme: 文件轨迹相关业务逻辑处理类
 */
class File_trace_service extends MY_Service
{
    public function __construct()
    {
        parent::__construct();
        $this->load->language("files");
        $this->load->library("traces");
        $this->load->model("file_trace_model");
    }

    /**
     * 获取文件轨迹列表的文件
     */
    public function get_trace_files($uid,$condition=array("deleted"=>0),$sort="ts",$direction="desc",$fields="id,name",$limit=false,$active="")
    {
        return $this->file_trace_model->get_trace_files($uid,$condition,$sort,$direction,$fields,$limit,$active);
    }

    /**
     * 获取文件的轨迹的日期
     * @param $fid
     * @param bool $limit
     * @return mixed
     */
    public function get_dates($fid,$sort="ts",$direction="desc",$limit=false)
    {
        return $this->file_trace_model->get_traces($fid,array("hidden"=>0),$sort,$direction,"id,ts",$limit,"ts");
    }


    /**
     * 获取文件轨迹
     * @param $fid 文件ID
     * @param array $condition 条件
     * @param string $fields 所需字段
     * @param bool $limit 条数
     * @param string $group
     * @return mixed
     */
    public function get_traces($fid,$condition=array("hidden"=>0),$sort="ts",$direction="desc",$fields="id,actor
,event,start,end,relation,ts,unsafe,hidden,file_id,actor_ip,actor_city",$limit=false,$group="")
    {
        return $this->file_trace_model->get_traces($fid,$condition,$sort,$direction,$fields,$limit,$group);
    }

    public function get_event_name($event)
    {
        $event_name = $this->lang->line("file_trace_event");
        return isset($event_name[$event])?$event_name[$event]:"";
    }

    /**
     * 截屏标识用户
     * @param $event 事件17
     * @param $uid 操作者uid
     * @return string
     */
    public function get_event_param_name($event, $uid) {
        $fields = array('id','mobile','nickname','email');
        $this->load->model('user_model');
        $actor = $this->user_model->get_user_info(array("id"=>$uid),$fields);

        if (! empty($actor['nickname'])) {
            $name = $actor['nickname'];
        } else if (! empty($actor['mobile'])) {
            $name = substr_replace($actor['mobile'],'****',3,4);
        } else {
            $name = $actor['email'];
        }


        $event_name = $this->lang->line("file_trace_event");
        return isset($event_name[$event]) ? trim(sprintf($event_name[$event], $name)) : "";
    }

    public function parse_child_policies($children)
    {
        if(empty($children))
        {
            return null;
        }
        $len = count($children);
        $data=array();
        $descriptions = $this->lang->line("file_trace_policy_description");
        foreach($children as $k=>$v)
        {
            //标记单双数
            if(($k+1) % 2 == 0)
            {
                $data[$k]['uneven'] = true;
            }
            else
            {
                $data[$k]['even'] = true;
            }
            //标记是否为最后一个
            if(($k +1 ) == $len)
            {
                $data[$k]['isLast'] = true;
            }
            if($v['start']==='0')
            {
                $v['start']="";
            }
            if($v['end']==='0')
            {
                $v['end']="";
            }
            //新建
            if($v['start'] == '' && $v['end'] != '')
            {
                if((int)$v['event']==Traces::EVENT_SET_LIFE_SPAN)
                {
                    $v['end'] = date("Y-m-d H:i:s",$v['end']);
                }
                $data[$k]['info'] = isset($descriptions[$v['event']])?sprintf($descriptions[$v['event']][0],$v['end']):"";
                $data[$k]['icon'] = "icon-add";
                if((int)$v['event']==Traces::EVENT_SET_READ_PWD)
                {
                    $data[$k]['copytext']=$v['end'];
                }
            }
            //修改
            elseif($v['start'] != '' && $v['end'] != '' )
            {
                if((int)$v['event']==Traces::EVENT_SET_LIFE_SPAN)
                {
                    $v['start'] = date("Y-m-d H:i:s",$v['start']);
                    $v['end'] = date("Y-m-d H:i:s",$v['end']);
                }
                $info = "";
                if (isset($descriptions[$v['event']])) {
                    #open_counter 打开次数,传一个参数
                    if ($v['event'] == 14) {
                        $info = sprintf($descriptions[$v['event']][1], $v['end']);

                    #其它修改传两个参数
                    } else {
                        $info = sprintf($descriptions[$v['event']][1],$v['start'],$v['end']);
                    }
                }

                $data[$k]['info'] = $info;
                $data[$k]['icon'] = "icon-edit";
                if((int)$v['event']==Traces::EVENT_SET_READ_PWD)
                {
                    $data[$k]['copytext']=$v['end'];
                }
            }
            //关闭
            elseif($v['start'] !='' && $v['end']=='')
            {
                if((int)$v['event']==Traces::EVENT_SET_LIFE_SPAN)
                {
                    $v['start'] = date("Y-m-d H:i:s",$v['start']);
                }
                $data[$k]['info'] = isset($descriptions[$v['event']])?sprintf($descriptions[$v['event']][2],$v['start']):"";
                $data[$k]['icon'] = "icon-destroy";
            }
        }
        return $data;
    }

    public function traces_format($traces,$start=0)
    {
        if(empty($traces))
        {
            return null;
        }
        $newTraces = array();
        $index = 0;
        foreach($traces as $key => $trace){
            if($trace['relation']>0)
            {
                continue;
            }
            $obj = array();
            $obj['tsHi'] = date('H:i', $trace['ts']);
            $obj['event'] = $trace['event'];

            if ($trace['event'] == Traces::EVENT_SCREEN_SHOT_FILE) {
                $obj['name'] = trim($this->get_event_param_name($trace['event'], $trace['actor']));
            } else {
                $obj['name'] = $this->get_event_name($trace['event']);
            }
            $obj['index'] = $start+$index++;
            $obj['unsafe'] = $trace['unsafe'];
            //按照天来分排
            $by_date = date("Y-m-d",$trace['ts']);
            $newTraces[$by_date]['ts'] = date('Y-m-d', $trace['ts']);
            //解析子列表
            if((int)$trace['event'] == Traces::EVENT_SET_POLICY)
            {
                $children_policies = Common::array_find_rows($traces,"relation",$trace['id']);
                $obj['hasOptions'] = $children_policies?true:false;
                //解析子策略
                $obj['options'] = $children_policies?$this->parse_child_policies($children_policies):null;
            }
            $newTraces[$by_date]['list'][] = $obj;
        }

        //if($this->_last_copy_group_key!==FALSE && $this->_last_copy_parent_key!==FALSE && $this->las)
        return array_values($newTraces);
    }

    /**
     * 轨迹翻页
     * @param $fid
     * @param string $where
     * @param string $limit
     * @param string $field
     */
    public function get_trace_list($fid, $where='', $limit='', $field='') {
        if (empty($fid)) return;

        return $this->file_trace_model->get_trace_list($fid, $where, $limit, $field);
    }

    /**
     * 格式化,拆分轨迹
     * @param $traces
     * @param int $start
     * @return array|void
     */
    public function list_format($traces,$start=0,$uid='')
    {
        if(empty($traces)) return;

        $newTraces = array();
        $index = 0;
        $date_tag = 0;  //日期标识
        foreach($traces as $key => $trace){
            $obj = array();
            $obj['id'] = $trace['id'];
            $obj['ts'] = $trace['ts'];
            $obj['event'] = $trace['event'];
            //$obj['name'] = $this->get_event_name($trace['event']);
            $obj['index'] = $start+$index++;
            $obj['unsafe'] = $trace['unsafe'];
            $obj['file_id'] = $trace['file_id'];

            if ($trace['event'] == Traces::EVENT_SCREEN_SHOT_FILE) {
                $event_name = $this->lang->line("file_trace_event");
                $obj['name'] = trim(sprintf($event_name[$trace['event']], ""));
            } else {
                $obj['name'] = $this->get_event_name($trace['event']);
            }

            //标识用户
            if (! empty($uid) && ($uid == $trace['actor']) ) {
                $owner = "我";
            } else {
                $owner = $trace['nickname'] ?: $trace['mobile'] ?: $trace['email'] ?: "匿名";
            }
            $obj['owner'] = $owner;

            $date_tmp = date('Ymd', $trace['ts']);
            if ($date_tmp !== $date_tag) {
                $obj['ts_f'] = '1';
                $date_tag = $date_tmp;
            } else {
                $obj['ts_f'] = '0';
            }

            $obj['hasOptions'] = false;
            //按照天来分排
            //$by_date = date("Y-m-d",$trace['ts']);
            //$newTraces[$by_date]['ts'] = date('Y-m-d', $trace['ts']);
            //解析子列表
            if((int)$trace['event'] == Traces::EVENT_SET_POLICY)
            {
                //拆分
                $trace_arr = explode(',', $trace['traces']);
                $trace_list = array();
                foreach ($trace_arr as $key => $value) {
                    $child_trace = explode('/', $value);
                    $convert = array(
                        'id' =>  $child_trace[0],
                        'event' => $child_trace[1],
                        'start' => $child_trace[2]?:'0',
                        'end' => $child_trace[3]?:'0'
                    );
                    $trace_list[] = $convert;
                }

                //echo json_encode($trace_list);die;
                $children_policies = $trace_list;
                $obj['hasOptions'] = $children_policies ? true : false;
                //解析子策略
                $obj['options'] = $children_policies ? $this->parse_child_policies($children_policies) : null;
            }
            //$newTraces[$by_date][] = $obj;
            $newTraces[] = $obj;
        }

        return array_values($newTraces);
    }
}
